package com.shoujifeng.snowmusic.player.http;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.R.integer;
import android.content.Context;
import android.util.Log;

import com.shoujifeng.snowmusic.db.DatabaseUtil;
import com.shoujifeng.snowmusic.player.interfaces.DownloadInterface;

/**
 * 下载管理类
 * BY Kress
 * @author Administrator
 *
 */
public class DownloadManager {
	
	private ArrayList<DownLoadFile> downLoadFiles;
	private DatabaseUtil databaseUtil;
	private ArrayList<HashMap<String, Object>> mDataList;
	private Context mContext;
	private int nowDown = -1;
	
	private DownloadInterface mInterface = null;
	
	private boolean bDownloadding = false;
	public DownloadManager(Context context) {
		downLoadFiles = new ArrayList<DownLoadFile>();
		databaseUtil = new DatabaseUtil(context);
		mDataList = new ArrayList<HashMap<String,Object>>();
		mContext = context;
	}
	
	public void setInterFace(DownloadInterface inter) {
		mInterface = inter;
	}
	
	public void stop(int index) {
		DownLoadFile  down = downLoadFiles.get(index);
		down.bStart = false;
		
		if(nowDown == index || nowDown == -1) {
			bDownloadding = false;
			
			startDownload();
		}
	}
	
	public void start(int index) {
		DownLoadFile  down = downLoadFiles.get(index);
		down.bStart = true;
		
		if(!bDownloadding)
			startDownload();
	}
	
	public void allStart() {
		for(int i=0; i<downLoadFiles.size(); i++) {
			DownLoadFile  down = downLoadFiles.get(i);
			down.bStart = true;
		}
		
		if(!bDownloadding)
			startDownload();
	}
	
	public void allStop()
	{
		for(int i=0; i<downLoadFiles.size(); i++) {
			DownLoadFile  down = downLoadFiles.get(i);
			down.bStart = false;
		}
	}
	
	public void deleteDown(int index) {
		stop(index);
		
		HashMap<String, Object> map = mDataList.get(index);
		
		File file = new File(GlobalValue.getSDcardPath() 
							+ GlobalValue.CacheFile+ "/" + map.get(ServerAccess.MUSIC_NAME).toString());
		deleteFile(file);
		
		databaseUtil.deleteDown(Integer.parseInt(map.get(ServerAccess.INDEX).toString()));
		
		mDataList.remove(index);
		downLoadFiles.remove(index);
	}
	
	public boolean getStartState(int index) {
		DownLoadFile  down = downLoadFiles.get(index);
		
		return down.bStart;
	}
	
	//从数据库中读取下载信息
	public void readDownload() {
		//预读
		
		mDataList = databaseUtil.getDownload(-1, 0);
		for(int i=0; i<mDataList.size(); i++) {
			
			HashMap<String, Object> map = mDataList.get(i);
			
			//转换过程
			String urlString = map.get(ServerAccess.URL).toString();
			int index = Integer.parseInt(map.get(ServerAccess.UID).toString());
			
			map.put(ServerAccess.INDEX, index);
			map.put(ServerAccess.FILE_URL, urlString);
			
			//String mp3Name = getFileName(map.get(ServerAccess.FILE_URL).toString());
					
			DownLoadFile down = new DownLoadFile();
			down.bStart = false;
			down.index = i;
			down.clenght = map.get(ServerAccess.PRO_MAX).toString();
			down.pro = Integer.parseInt(map.get(ServerAccess.PRO).toString());
			down.setDownloadData(index, 
					urlString,
					GlobalValue.getSDcardPath() + GlobalValue.CacheFile,
					map.get(ServerAccess.MUSIC_NAME).toString());
			down.setInterface(downloadInterface);
			
			downLoadFiles.add(down);
		}
	}
	
	public ArrayList<HashMap<String, Object>> getDataList()
	{
		return mDataList;
	}
	
	public int getSize()
	{
		return mDataList.size();
	}
	
	/**
	 * 加入下载队列
	 * @param map  uid,name,singer,icon_url,file_url,url
	 */
	public void addDownload(HashMap<String, Object> map) {
		
		//初始进度
		map.put(ServerAccess.PRO, 0);
		map.put(ServerAccess.PRO_MAX, 100);
		
		databaseUtil.insertDownload(Integer.parseInt(map.get(ServerAccess.INDEX).toString()),
				map.get(ServerAccess.MUSIC_NAME).toString(),
				map.get(ServerAccess.SINGER).toString(),
				map.get(ServerAccess.ICON_URL).toString(), 
				GlobalValue.getSDcardPath() + GlobalValue.CacheFile+ "/" + map.get(ServerAccess.MUSIC_NAME).toString(), 
				map.get(ServerAccess.MUSIC_FILE).toString());
		
		
		DownLoadFile down = new DownLoadFile();
		down.bStart = true;
		down.setDownloadData(Integer.parseInt(map.get(ServerAccess.INDEX).toString()), 
				map.get(ServerAccess.MUSIC_FILE).toString(),
				GlobalValue.getSDcardPath() + GlobalValue.CacheFile,
				map.get(ServerAccess.MUSIC_NAME).toString());
		down.pro = 0;
		down.index = downLoadFiles.size();
		//设置回调
		down.setInterface(downloadInterface);
		
		downLoadFiles.add(down);
		mDataList.add(map);
		
		if(!bDownloadding) {
			startDownload();
		}
	}
	
	//获取文件名
	public String getFileName(String pathandname){
		
		int start=pathandname.lastIndexOf("/");
		if(start!=-1){
			return pathandname.substring(start+1);	
		}else{
			return null;
		}
	}
	
	//寻找一个可以下载的来下载
	public void startDownload() {
		
		int count = downLoadFiles.size();
		for(int i=0; i<count; i++) {
			DownLoadFile down = downLoadFiles.get(i);
			if(down.bStart) {
				down.startDownload(down.pro);
				nowDown = i;
				bDownloadding = true;
				return;
			}
		}
		
		nowDown = -1;
	}
	
	//回调通知
	private DownloadInterface downloadInterface = new DownloadInterface() {
		
		@Override
		public void downloadOver(int index, int length, String path) {
			
			DownLoadFile down = downLoadFiles.get(index);
			//设置及删除下载
			databaseUtil.updateDownload(down.uid, length +"", down.clenght, path, 1);
			
			downLoadFiles.remove(index);
			mDataList.remove(index);
			
			bDownloadding = false;
			startDownload(); 
			
			nowDown = -1;
			
			if(mInterface != null){
				mInterface.downloadOver(index, length, path);
			}
		}

		@Override
		public void downloadding(int index, int now, int length, boolean write) {
			// TODO Auto-generated method stub
			
			DownLoadFile down = downLoadFiles.get(index);
			if(write)
				databaseUtil.updateDownload(down.uid, now+"", down.clenght, "", 0);
			
			if(mInterface != null){
				mInterface.downloadding(index, now, length, false);
			}
		}

	};
	
	
	public void deleteFile(File file) {
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		}
	}
}
